<?php
namespace app\admin\controller;
/*

 All rights Reserved, Designed By www.youyacao.com
 @Description:基础方法文件
 @author:成都市一颗优雅草科技有限公司
 @version 优雅草松鼠聚合直播系统
 需要商业用途或者定制开发等可访问songshu.youyacao.com  联系QQ:2853810243 422108995 23625059584
 正版系统查询系统 zhengbancha.youyacao.com

*/
use \think\Db;

class Base
{
    public $user = NULL;

    public function __construct(){
        $info = $this->userinfo();
        if($info['code'] == -1) $this->error('no-login');
        if(Db::name("user")->where("id",$info['data']['id'])->value("delete_time")>0) $this->error("此账号已被封停");
    }
    protected function success($data,$msg='')
    {
        $data = ['code'=>1,'data'=>$data,'msg'=>$msg];
        header('Content-Type:application/json; charset=utf-8');
        echo json_encode($data);
        die();
    }

    protected function error($msg = '')
    {
        $data = ['code'=>-1,'msg'=>$msg ? $msg : 'error'];
        header('Content-Type:application/json; charset=utf-8');
        echo json_encode($data);
        die();
    }

    public function userinfo(){
        $user_id = session('login_user_id');
        $user = Db::name("user")->where('id',$user_id)->where('user_type','between','admin,daili')->find();
        if(!$user){
            session('login_user_id',null);
            return ['code'=>-1,'msg'=>'no-login'];
        }
        $this->user = $user;
        $data = ['id'=>$user['id'],'username'=>$user['username'],'usernick'=>$user['usernick'],'tuijianma'=>$user['tuijianma'],'qq'=>$user['qq'],
            'money'=>number_format($user['money'],2),'user_type'=>$user['user_type'],'last_login_time'=>date('Y-m-d H:i:s',$user['last_login_time'])];
        return ['code'=>1,'data'=>$data,'msg'=>'用户已登陆'];
    }

    protected function onlyAdmin(){
        if($this->user['user_type'] != 'admin') $this->error('此功能只能管理员才能使用');
    }

    protected function get_client_ip($type = 0) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if(isset($_SERVER['HTTP_X_REAL_IP'])){//nginx 代理模式下，获取客户端真实IP
            $ip=$_SERVER['HTTP_X_REAL_IP'];
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
        }else{
            $ip=$_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}
